<!--
 * @Descripttion: 规格值
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-10 15:49:20
 -->
<template>
  <div>
    <el-button v-for="(item,index) in data" :key="index" icon="el-icon-delete" type="default" @click="()=> {btnDelData(item)}">
      {{ item.name }}
    </el-button>
    <div class="margin-t10">
      <el-input v-model="speceNew" style="width:100px" />
      <el-button type="primary" @click="btnAddData">新增规格值</el-button>
    </div>
  </div>
</template>
<script>
import { oftenuse } from '@/libs/mixins'
import { saveData, delData } from '@/api/bsd/specs.js'
import { Promise } from 'q'

export default {
  name: 'SpecsValue',
  mixins: [oftenuse],
  props: {
    pId: {
      type: String,
      required: true
    },
    value: {
      type: Array,
      default: () => { return [] }
    }
  },
  data() {
    return {
      data: [],
      speceNew: null
    }
  },
  watch: {
    'data': {
      handler(data) {
        this.$emit('input', data)
      }
    }
  },
  created() {
    this.data = this.value
  },
  methods: {
    btnAddData() {
      const sp = this.speceNew
      if (sp === '' || !sp) {
        return this.$message.error('请输入规格值！')
      }
      const params = {
        name: sp,
        pid: this.pId
      }
      this.saveData(params).then(data => {
        this.data.push(data)
        this.speceNew = null
      })
    },
    btnDelData(row) {
      const data = this.data
      const { id } = row
      this.delData(id).then(_ => {
        const index = data.indexOf(row)
        data.splice(index, 1)
      })
    },
    delData(specsId) {
      return new Promise((resolve, reject) => {
        delData(specsId).then(res => {
          if (res.data.flag) {
            this.$notify.success({ title: res.data.title })
            resolve()
          }
        })
      })
    },
    saveData(params) {
      return new Promise((resolve, reject) => {
        saveData(params).then(res => {
          if (res.data.flag) {
            resolve(res.data.data)
            this.$notify.success({ title: '保存成功！' })
          } else {
            this.$notify.error({ title: '保存失败！', message: res.data.message || '' })
          }
        })
      })
    }
  }
}
</script>

<style scoped>
</style>
